package com.wangyk.jpaproject.service.impl;

import com.wangyk.jpaproject.repository.ProductInfoRepository;
import com.wangyk.jpaproject.service.ProductInfoService;
import com.wangyk.rabbitmqcommon.model.jpaproject.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class ProductInfoServiceImpl implements ProductInfoService
{
    @Autowired
    private ProductInfoRepository productInfoRepository;

    public List<ProductInfo> findAll()
    {
        return productInfoRepository.findAll();
    }

    @Override
    public List<ProductInfo> findAllByProductId(Integer productId)
    {
        return productInfoRepository.findAllByProductId(productId);
    }

    @Override
    public ProductInfo saveProductInfo(ProductInfo productInfo)
    {
        //参数中有categoryId说明是修改，没有说明是新增操作。
        if (productInfo.getCategoryId() == null)
        {
            productInfo.setCreateTime(new Date());
        }
        return productInfoRepository.save(productInfo);
    }

    @Override
    public ProductInfo saveProductInfoBySelective(ProductInfo productInfo)
    {
        if (productInfo.getProductId() == null)
        {
            productInfo.setCreateTime(new Date());
            return productInfoRepository.save(productInfo);
        }
        List<ProductInfo> productInfoList = productInfoRepository.findAllByProductId(productInfo.getProductId());
        //查询原记录中的值
        ProductInfo oldProductInfo = productInfoList.get(0);
        //将新的值替换
        log.info("service替换前的productInfo:"+productInfo.toString());
        BeanUtils.copyProperties(oldProductInfo, productInfo, getNoNullProperties(productInfo));
        log.info("service替换后的productInfo:"+productInfo.toString());
        return productInfoRepository.save(productInfo);
    }

    /**
     * @param target 目标源数据
     * @return 将目标源中不为空的字段取出
     */
    private static String[] getNoNullProperties(Object target)
    {
        BeanWrapper srcBean = new BeanWrapperImpl(target);
        PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
        Set<String> noEmptyName = new HashSet<>();
        for (PropertyDescriptor p : pds)
        {
            Object value = srcBean.getPropertyValue(p.getName());
            if (value != null)
                noEmptyName.add(p.getName());
        }
        String[] result = new String[noEmptyName.size()];
        return noEmptyName.toArray(result);
    }

}
